package com.ji.server;

/**
 * Created by 1 on 2017/2/23.
 */
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.*;
import com.rabbitmq.client.QueueingConsumer.Delivery;

import java.io.IOException;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

public class CloudClient {

    public static final String RPC_QUEUE_NAME = "rpc_cloud";

    public static void main(String[] args) throws IOException, ShutdownSignalException, ConsumerCancelledException, InterruptedException,TimeoutException {

        ConnectionFactory connFac = new ConnectionFactory() ;
        connFac.setHost("192.168.1.106");
        connFac.setPort(5672);
        connFac.setUsername("root");
        connFac.setPassword("root");
        Connection conn = connFac.newConnection();
        Channel channel = conn.createChannel() ;
        System.out.println();
        //响应QueueName ，服务端将会把要返回的信息发送到该Queue
        String responseQueue = channel.queueDeclare().getQueue() ;

        String correlationId = UUID.randomUUID().toString() ;

        BasicProperties props = new BasicProperties.Builder()
                .replyTo(responseQueue)
                .correlationId(correlationId)
                .build();




        QueueingConsumer consumer = new QueueingConsumer(channel)   ;

        channel.basicConsume( responseQueue , consumer) ;

        while(true){
            //Thread.sleep(1*1000);
            System.out.println("输入要发送的");
            Scanner sc = new Scanner(System.in);
            String message = sc.next();
            channel.basicPublish( "" , RPC_QUEUE_NAME , props ,  message.getBytes("UTF-8"));
            System.out.println(message+"发送");
            System.out.println();
            Delivery delivery = consumer.nextDelivery() ;
            if(delivery.getProperties().getCorrelationId().equals(correlationId)){
                String result = new String(delivery.getBody()) ;
                System.out.println(result);
            }

        }
    }

}